package cn.stylefeng.guns.generator.engine.base;

import cn.hutool.core.util.StrUtil;
import cn.stylefeng.guns.generator.engine.config.*;
import cn.stylefeng.guns.generator.executor.config.GunsGeneratorConfig;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.sun.javafx.PlatformUtil;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.Data;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.ClasspathResourceLoader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * ADI项目模板生成 引擎
 *
 * @author fengshuonan
 * @date 2017-05-07 22:15
 */
public class GunsTemplateEngine {

    private GroupTemplate groupTemplate;
    private GunsGeneratorConfig gunsGeneratorConfig;
    private ControllerConfig controllerConfig;
    private ContextConfig contextConfig;
    PageConfig pageConfig;
    public GunsTemplateEngine(GunsGeneratorConfig gunsGeneratorConfig) {
        this.gunsGeneratorConfig = gunsGeneratorConfig;
        initBeetlEngine();
        pageConfig = new PageConfig(gunsGeneratorConfig);
        controllerConfig = new ControllerConfig(gunsGeneratorConfig);
        contextConfig = gunsGeneratorConfig.getContextConfig();
    }



    protected void configTemplate(Template template) {
        template.binding("controller", controllerConfig);
        template.binding("context", contextConfig);
        template.binding("dao", new DaoConfig(gunsGeneratorConfig));
        template.binding("service", new ServiceConfig(gunsGeneratorConfig));
        template.binding("sqls", gunsGeneratorConfig.getSqlConfig());
        template.binding("table", gunsGeneratorConfig.getTableInfo());
        template.binding("package", gunsGeneratorConfig.getPackageConfig());
        template.binding("reqparam",new ReqParamConfig(gunsGeneratorConfig));
    }

    protected void generateFile(String template, String filePath) {
        Template pageTemplate = groupTemplate.getTemplate(template);
        configTemplate(pageTemplate);
        if (PlatformUtil.isWindows()) {
            filePath = filePath.replaceAll("/+|\\\\+", "\\\\");
        } else {
            filePath = filePath.replaceAll("/+|\\\\+", "/");
        }
        File file = new File(filePath);
        File parentFile = file.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(file);
            pageTemplate.renderTo(fileOutputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void start(PackageConfig packageConfig) {
        //生成模板
        generateController();
        generatePageAddHtml();
        generatePageEditHtml();
        generatePageJs();
        generateSqls();
        generateReqParam();
        generateDetailPage();
    }

    protected void generatePageEditHtml() {
        String path = StrUtil.format(contextConfig.getProjectPath() + pageConfig.getPageEditPathTemplate(),
                contextConfig.getBizEnName(), contextConfig.getBizEnName());
        generateFile(contextConfig.getTemplatePrefixPath() + "/page_edit.html.btl", path);
        System.out.println("生成编辑页面成功!");

        String pathEditJs = StrUtil.format(contextConfig.getProjectPath() + pageConfig.getPageEditJsPathTemplate(),
                contextConfig.getBizEnName(), contextConfig.getBizEnName());
        generateFile(contextConfig.getTemplatePrefixPath() + "/page_edit.js.btl", pathEditJs);
        System.out.println("生成页面edit js成功!");
    }

    protected void generatePageAddHtml() {
        String path = StrUtil.format(contextConfig.getProjectPath() + pageConfig.getPageAddPathTemplate(),
                contextConfig.getBizEnName(), contextConfig.getBizEnName());
        generateFile(contextConfig.getTemplatePrefixPath() + "/page_add.html.btl", path);
        System.out.println("生成添加页面成功!");

        String pathAddJs = StrUtil.format(contextConfig.getProjectPath() + pageConfig.getPageAddJsPathTemplate(),
                contextConfig.getBizEnName(), contextConfig.getBizEnName());
        generateFile(contextConfig.getTemplatePrefixPath() + "/page_add.js.btl", pathAddJs);
        System.out.println("生成页面添加js成功!");
    }


    protected void generatePageJs() {
        String path = StrUtil.format(contextConfig.getProjectPath() + pageConfig.getPageJsPathTemplate(),
                contextConfig.getBizEnName(), contextConfig.getBizEnName());
        generateFile(contextConfig.getTemplatePrefixPath() + "/page.js.btl", path);
        System.out.println("生成页面js成功!");

        String pagePath = "/src/main/webapp/pages/modular/" + contextConfig.getModuleName() + "/{}/{}.html";
        String pathListHtml = StrUtil.format(contextConfig.getProjectPath() + pagePath, contextConfig.getBizEnName(), contextConfig.getBizEnName());
        generateFile(contextConfig.getTemplatePrefixPath() + "/page.html.btl", pathListHtml);
        System.out.println("生成页面成功!");

    }

    protected void generateDetailPage() {
        String path2 = StrUtil.format(contextConfig.getProjectPath() + pageConfig.getPageDetailPathTemplate(),
                contextConfig.getBizEnName(), contextConfig.getBizEnName());
        generateFile(contextConfig.getTemplatePrefixPath() + "/page_detail.html.btl", path2);
        System.out.println("生成页面成功!");

        String path3 = StrUtil.format(contextConfig.getProjectPath() + pageConfig.getPageDetailJSPathTemplate(),
                contextConfig.getBizEnName(), contextConfig.getBizEnName());
        generateFile(contextConfig.getTemplatePrefixPath() + "/page_detail.js.btl", path3);
        System.out.println("生成页面成功!");
    }


    protected void generateController() {
        String controlPath =   "/src/main/java/"+contextConfig.getProPackage().replaceAll("\\.","/")+"/modular/" + contextConfig.getModuleName() + "/controller/{}Controller.java";;
        String controllerPath = StrUtil.format(contextConfig.getProjectPath() + controlPath, StrUtil.upperFirst(contextConfig.getBizEnName()));
        generateFile(contextConfig.getTemplatePrefixPath() + "/Controller.java.btl", controllerPath);
        System.out.println("生成控制器成功!");
    }

    protected void generateReqParam(){
        String reqListParamPath = "/src/main/java/"+contextConfig.getProPackage().replaceAll("\\.","/")+"/modular/" + contextConfig.getModuleName() + "/model/reqparam/{}ListParam.java";;
        String reqJavaPath = StrUtil.format(contextConfig.getProjectPath() + reqListParamPath,StrUtil.upperFirst(contextConfig.getBizEnName()));
        generateFile(contextConfig.getTemplatePrefixPath() + "/reqparam.java.btl", reqJavaPath);
        System.out.println("生成ReqParam成功!");
    }
    protected void generateSqls() {
        String path = StrUtil.format(contextConfig.getProjectPath() + gunsGeneratorConfig.getSqlConfig().getSqlPathTemplate(),
                StrUtil.upperFirst(contextConfig.getBizEnName()));
        generateFile(contextConfig.getTemplatePrefixPath() + "/menu_sql.sql.btl", path);
        System.out.println("生成sql成功!");
    }

    protected void initBeetlEngine() {
        Properties properties = new Properties();
        properties.put("RESOURCE.root", "");
        properties.put("DELIMITER_STATEMENT_START", "<%");
        properties.put("DELIMITER_STATEMENT_END", "%>");
        properties.put("HTML_TAG_FLAG", "##");
        Configuration cfg = null;
        try {
            cfg = new Configuration(properties);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader();
        groupTemplate = new GroupTemplate(resourceLoader, cfg);
        groupTemplate.registerFunctionPackage("tool", new ToolUtil());
    }
}
